package com.daxia.bumall.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.daxia.bumall.common.Logs;

@Component(value = "myAuthenticationFailureHandler")
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

	@Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
		if (exception instanceof UsernameNotFoundException) {
			Logs.COMMON.debug("exception instanceof UsernameNotFoundException");
		} else if (exception instanceof NotAuthException) {
			Logs.COMMON.debug("exception instanceof NotAuthException");
		} else {
			Logs.COMMON.debug(ToStringBuilder.reflectionToString(exception));
		}
		if ("NotAuth".equals(exception.getMessage())) {
			request.setAttribute("loginError", "对不起，您尚未通过平台认证，还不能进行登录，请等待平台验证结果");
		} else if ("NormalUser".equals(exception.getMessage())) {
			request.setAttribute("loginError", "普通用户不允许登陆");
		} else {
			request.setAttribute("loginError", "用户名或密码不正确");
		}
		request.getRequestDispatcher("user/login").forward(request, response);
    }

}
